import { Component, OnInit, OnDestroy, ViewChild, ElementRef, AfterViewInit, NgZone } from '@angular/core';
import { SignalrService } from '../../shared/services/signalr.service';
import { StockDataService } from '../../shared/services/stock-data.service';
import { Subscription, interval } from 'rxjs';
import * as echarts from 'echarts';
import { CommonModule } from '@angular/common';
import { NgxEchartsModule, NGX_ECHARTS_CONFIG } from 'ngx-echarts';
import { FormsModule } from '@angular/forms';
import { RouterModule } from '@angular/router';

@Component({
  selector: 'app-stock-dashboard',
  templateUrl: './stock-dashboard.component.html',
  styleUrls: ['./stock-dashboard.component.scss'],
  standalone: true,
  imports: [CommonModule, NgxEchartsModule, FormsModule, RouterModule],
  providers: [
    {
      provide: NGX_ECHARTS_CONFIG,
      useFactory: () => ({ echarts })
    }
  ]
})
export class StockDashboardComponent implements OnInit, OnDestroy, AfterViewInit {
  // 仪表盘数据
  dashboardData: any = null;
  
  // 加载状态
  loading = true;
  
  // 刷新状态
  refreshing = false;
  
  // 更新时间
  updateTime: Date | null = null;

  // 图表配置
  warehouseChartOption: any = {};
  typeChartOption: any = {};
  trendChartOption: any = {};
  
  // 图表实例
  private warehouseChart: echarts.ECharts | null = null;
  private typeChart: echarts.ECharts | null = null;

  // 低库存物品列表
  lowStockItems: any[] = [];
  
  // 库存统计数据
  stockStats: any = {
    totalStock: 0,
    totalAmount: 0,
    warehouseCount: 0,
    typeCount: 0
  };
  
  // 按仓库分组的库存数据
  stockByWarehouse: any[] = [];
  
  // 按类型分组的库存数据
  stockByType: any[] = [];
  
  // 订阅对象
  private subscription: Subscription = new Subscription();
  private autoRefreshSubscription: Subscription | null = null;

  // 自动刷新设置
  autoRefreshEnabled = false;
  autoRefreshInterval = 60; // 默认60秒
  autoRefreshIntervalOptions = [
    { label: '30秒', value: 30 },
    { label: '1分钟', value: 60 },
    { label: '5分钟', value: 300 },
    { label: '10分钟', value: 600 },
    { label: '30分钟', value: 1800 }
  ];

  // 获取图表容器引用
  @ViewChild('warehouseChartContainer') warehouseChartContainer!: ElementRef;
  @ViewChild('typeChartContainer') typeChartContainer!: ElementRef;

  constructor(
    private signalrService: SignalrService,
    private stockDataService: StockDataService,
    private ngZone: NgZone
  ) { }

  ngOnInit(): void {
    // 加载用户刷新偏好设置
    this.loadRefreshPreferences();
    
    // 使用共享的库存数据服务代替SignalR连接
    this.loading = true;
    
    // 订阅库存统计数据
    this.subscription.add(
      this.stockDataService.stockStats$.subscribe(stats => {
        this.stockStats = stats;
        this.dashboardData = {
          totalStock: stats.totalStock,
          totalAmount: stats.totalAmount,
          stockByWarehouse: this.stockByWarehouse,
          stockByType: this.stockByType
        };
        this.loading = false;
      })
    );
    
    // 订阅仓库分布数据
    this.subscription.add(
      this.stockDataService.stockByWarehouse$.subscribe(data => {
        this.stockByWarehouse = data;
        if (this.dashboardData) {
          this.dashboardData.stockByWarehouse = data;
        }
        this.updateCharts();
      })
    );
    
    // 订阅类型分布数据
    this.subscription.add(
      this.stockDataService.stockByType$.subscribe(data => {
        this.stockByType = data;
        if (this.dashboardData) {
          this.dashboardData.stockByType = data;
        }
        this.updateCharts();
      })
    );
    
    // 订阅低库存物品数据
    this.subscription.add(
      this.stockDataService.lowStockItems$.subscribe(data => {
        this.lowStockItems = data;
      })
    );
    
    // 订阅更新时间
    this.subscription.add(
      this.stockDataService.lastUpdateTime$.subscribe(time => {
        this.updateTime = time;
        this.refreshing = false;
      })
    );
    
    // 初始化时刷新一次数据
    this.stockDataService.refreshData();
    
    // 如果启用了自动刷新，开始自动刷新
    if (this.autoRefreshEnabled) {
      this.startAutoRefresh();
    }
  }

  ngAfterViewInit(): void {
    // 延长图表初始化时间，确保DOM已完全渲染
    setTimeout(() => {
      this.initCharts();
      // 首次初始化后，再次延迟刷新以确保图表正确显示
      setTimeout(() => {
        this.resizeCharts();
        this.updateCharts();
      }, 500);
    }, 800);

    // 添加窗口大小变化监听，以便调整图表大小
    window.addEventListener('resize', this.resizeCharts.bind(this));
  }

  /**
   * 刷新数据
   */
  refreshData(): void {
    if (this.refreshing) return;
    
    this.refreshing = true;
    console.log('手动刷新库存仪表盘数据');
    
    // 直接调用库存数据服务的刷新方法
    this.stockDataService.refreshData();
    
    // 3秒后如果仍在刷新，则重置状态（以防请求卡住）
    setTimeout(() => {
      if (this.refreshing) {
        this.refreshing = false;
      }
    }, 3000);
  }

  /**
   * 切换自动刷新状态
   */
  toggleAutoRefresh(): void {
    this.autoRefreshEnabled = !this.autoRefreshEnabled;
    
    if (this.autoRefreshEnabled) {
      this.startAutoRefresh();
    } else {
      this.stopAutoRefresh();
    }
    
    // 保存用户偏好
    this.saveRefreshPreferences();
  }
  
  /**
   * 更改刷新间隔
   */
  changeRefreshInterval(): void {
    // 如果当前正在自动刷新，需要重启自动刷新以应用新间隔
    if (this.autoRefreshEnabled) {
      this.stopAutoRefresh();
      this.startAutoRefresh();
    }
    
    // 保存用户偏好
    this.saveRefreshPreferences();
  }
  
  /**
   * 开始自动刷新
   */
  private startAutoRefresh(): void {
    // 先停止现有的自动刷新
    this.stopAutoRefresh();
    
    // 创建新的刷新订阅
    this.autoRefreshSubscription = interval(this.autoRefreshInterval * 1000).subscribe(() => {
      console.log(`自动刷新 - 间隔${this.autoRefreshInterval}秒`);
      this.refreshData();
    });
  }
  
  /**
   * 停止自动刷新
   */
  private stopAutoRefresh(): void {
    if (this.autoRefreshSubscription) {
      this.autoRefreshSubscription.unsubscribe();
      this.autoRefreshSubscription = null;
    }
  }
  
  /**
   * 保存刷新偏好到本地存储
   */
  private saveRefreshPreferences(): void {
    const preferences = {
      autoRefreshEnabled: this.autoRefreshEnabled,
      autoRefreshInterval: this.autoRefreshInterval
    };
    
    localStorage.setItem('stockDashboardRefreshPreferences', JSON.stringify(preferences));
  }
  
  /**
   * 从本地存储加载刷新偏好
   */
  private loadRefreshPreferences(): void {
    const savedPreferences = localStorage.getItem('stockDashboardRefreshPreferences');
    
    if (savedPreferences) {
      try {
        const preferences = JSON.parse(savedPreferences);
        this.autoRefreshEnabled = preferences.autoRefreshEnabled || false;
        this.autoRefreshInterval = preferences.autoRefreshInterval || 60;
      } catch (e) {
        console.error('加载刷新偏好出错:', e);
      }
    }
  }

  /**
   * 初始化图表
   */
  private initCharts(): void {
    this.ngZone.runOutsideAngular(() => {
      try {
        console.log('初始化图表...');
        // 初始化仓库分布图表
        if (!this.warehouseChart && this.warehouseChartContainer) {
          const element = this.warehouseChartContainer.nativeElement;
          if (element) {
            console.log('初始化仓库图表容器:', element);
            this.warehouseChart = echarts.init(element);
            
            // 为空数据准备默认图表配置
            if (!this.stockByWarehouse || this.stockByWarehouse.length === 0) {
              const defaultOption = this.getDefaultWarehouseChartOption();
              this.warehouseChart.setOption(defaultOption);
            }
          } else {
            console.error('仓库图表容器元素未找到');
          }
        } else {
          console.log('仓库图表已存在或容器引用不存在');
        }

        // 初始化货品类型图表
        if (!this.typeChart && this.typeChartContainer) {
          const element = this.typeChartContainer.nativeElement;
          if (element) {
            console.log('初始化类型图表容器:', element);
            this.typeChart = echarts.init(element);
            
            // 为空数据准备默认图表配置
            if (!this.stockByType || this.stockByType.length === 0) {
              const defaultOption = this.getDefaultTypeChartOption();
              this.typeChart.setOption(defaultOption);
            }
          } else {
            console.error('类型图表容器元素未找到');
          }
        } else {
          console.log('类型图表已存在或容器引用不存在');
        }
        
        // 如果已有数据，立即更新图表
        if ((this.stockByWarehouse && this.stockByWarehouse.length > 0) || 
            (this.stockByType && this.stockByType.length > 0)) {
          console.log('更新图表数据...');
          this.updateCharts();
        }
      } catch (error) {
        console.error('初始化图表时出错:', error);
      }
    });
  }

  /**
   * 调整图表大小
   */
  private resizeCharts(): void {
    this.ngZone.runOutsideAngular(() => {
      if (this.warehouseChart) {
        this.warehouseChart.resize();
      }

      if (this.typeChart) {
        this.typeChart.resize();
      }
    });
  }

  /**
   * 更新所有图表
   */
  updateCharts(): void {
    // 确保数据和图表实例都已准备就绪
    if (this.warehouseChart && this.typeChart) {
      this.updateWarehouseChart();
      this.updateTypeChart();
    } else {
      console.log('图表实例未初始化，尝试重新初始化图表...');
      this.initCharts();
    }
  }

  /**
   * 更新仓库分布图
   */
  private updateWarehouseChart(): void {
    // 检查是否有图表实例和数据
    if (!this.warehouseChart) {
      console.warn('仓库图表实例不存在，跳过更新');
      return;
    }

    try {
      // 检查数据是否有效
      let warehouseData = this.stockByWarehouse || [];
      
      // 如果数据为空，使用默认数据
      if (warehouseData.length === 0) {
        warehouseData = [
          { warehouseName: '主仓库', stockCount: 100, stockAmount: 50000 },
          { warehouseName: '办公仓库', stockCount: 80, stockAmount: 40000 },
          { warehouseName: '食品仓库', stockCount: 50, stockAmount: 20000 }
        ];
        console.warn('仓库数据为空，使用默认数据');
      }
      
      // 处理图表数据
      const seriesData = warehouseData.map(item => {
        return {
          name: item.warehouseName,
          value: item.stockCount
        };
      });

      // 图表选项
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: warehouseData.map(item => item.warehouseName)
        },
        series: [
          {
            name: '仓库库存',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: true
            },
            data: seriesData
          }
        ]
      };

      // 设置图表选项
      this.warehouseChart.setOption(option, true);
      console.log('仓库分布图更新成功');
    } catch (error) {
      console.error('更新仓库分布图表时出错:', error);
      
      // 设置一个简单的错误图表
      const errorOption = {
        title: {
          text: '数据加载错误',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        series: [
          {
            name: '仓库库存',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 1, name: '数据错误' }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      
      if (this.warehouseChart) {
        this.warehouseChart.setOption(errorOption);
      }
    }
  }
  
  /**
   * 更新类型分布图表
   */
  private updateTypeChart(): void {
    if (!this.typeChart) {
      return;
    }
    
    try {
      // 如果没有数据，显示空数据状态
      if (!this.stockByType || this.stockByType.length === 0) {
        this.typeChart.setOption(this.getDefaultTypeChartOption());
        return;
      }

      // 按库存量排序，便于查看
      const sortedData = [...this.stockByType].sort((a, b) => b.stockCount - a.stockCount);
      
      // 准备类型分布柱状图数据
      const typeOption = {
        title: {
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: sortedData.map(item => item.goodsType),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '库存数量'
        },
        series: [
          {
            name: '库存数量',
            type: 'bar',
            data: sortedData.map(item => ({
              value: item.stockCount,
              itemStyle: {
                color: function() {
                  // 随机颜色，每次保持一致
                  const colors = [
                    '#5470c6', '#91cc75', '#fac858', '#ee6666',
                    '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
                  ];
                  return colors[Math.floor(Math.random() * colors.length)];
                }()
              }
            })),
            label: {
              show: true,
              position: 'top'
            }
          }
        ]
      };
      
      this.typeChart.setOption(typeOption, true);
    } catch (error) {
      console.error('更新类型图表出错:', error);
    }
  }
  
  /**
   * 获取默认的仓库图表配置（无数据状态）
   */
  private getDefaultWarehouseChartOption(): any {
    return {
      title: {
        text: '暂无仓库分布数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'item'
      },
      series: [
        {
          type: 'pie',
          radius: '60%',
          data: [],
          label: {
            show: false
          }
        }
      ]
    };
  }
  
  /**
   * 获取默认的类型图表配置（无数据状态）
   */
  private getDefaultTypeChartOption(): any {
    return {
      title: {
        text: '暂无货品类型分布数据',
        left: 'center',
        top: 'center',
        textStyle: {
          color: '#999',
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: []
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          type: 'bar',
          data: []
        }
      ]
    };
  }

  ngOnDestroy(): void {
    // 取消订阅
    this.subscription.unsubscribe();
    
    // 停止自动刷新
    this.stopAutoRefresh();

    // 移除窗口大小变化监听
    window.removeEventListener('resize', this.resizeCharts.bind(this));

    // 销毁图表实例
    if (this.warehouseChart) {
      this.warehouseChart.dispose();
      this.warehouseChart = null;
    }

    if (this.typeChart) {
      this.typeChart.dispose();
      this.typeChart = null;
    }
  }
} 